package com.pfe.myrobot;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;
import android.widget.Toast;

import com.pfe.myrobot.RobotReceiver.OnCallReceiverListener;
import com.pfe.myrobot.WifiStateReceiver.OnGameCreatedListener;
import com.pfe.myrobot.WifiStateReceiver.OnWifiPowerListener;
import com.pfe.myrobot.WifiStateReceiver.OnWifiStateListener;

@SuppressWarnings("deprecation")
public class StartMenuActivity extends Activity implements OnWifiPowerListener,	OnWifiStateListener, OnGameCreatedListener {

	// Network info
	public static final String SERVERIP = "192.168.137.1";
	public static final int SERVERPORT = 9999;

	// Keys for SharedPreferences
	public final static String PSEUDO = "pseudo";
	public final static String ALWAYS = "always";
	public final static String NAME = "name";
	
	//Game settings
	public final static int HEALTH_MIN = 10;
	public final static int HEALTH_MAX = 200;
	public final static int TIME_MIN = 5;
	public final static int TIME_MAX = 30;
	
	//Dialog showing flag
	public static boolean DIALOG_IS_SHOWING = false;

	// SharedPreferences
	private SharedPreferences configuration;
	public static String pseudo = "";
	public static String myName = "";
	public static boolean always = false;	

	// WiFi Management
	private ConnectivityManager networkManager;
	private WifiManager wifiManager;
	private WifiStateReceiver wifiReceiver;
	private IntentFilter actionFilter;

	// Main Interface
	private ImageView background_top, background_bottom;
	private TextView wifiName;
	private ImageView pressStart, title, playMode, freeMode, wifiLevel;
	private View wifiBackground;

	// Dialog Interface
	private AlertDialog enableWifi, pseudoAlert, robotAlert, nameAlert, timeAlert, configAlert, waitAlert, callAlert;
	private AlertDialog.Builder alertBuilder, pseudoBuilder, robotBuilder, nameBuilder, timeBuilder, configBuilder, waitBuilder, callBuilder;
	private View pseudoLayout, nameLayout, paramLayout, waitLayout;
	private EditText pseudoValue, nameValue;
	private ProgressBar lifeLevel, timeLevel;
	private ImageView lifeMore, lifeLess, timeMore, timeLess;
	private CheckBox checkTimeLimited;
	private TextView lifeValue, timeValue;

	// Settings Interface
	private SlidingDrawer settings;
	private ImageView handle;
	private TextView pseudoText, robotName;
	private Button changePseudo, changeRobot, changeName;
	private CheckBox alwaysCheck;
	
	
	//New game
	private RobotReceiver robotReceiver;
	private NewGameParameters newGameParam;
	
	//Other Variables
	private boolean holoIsOpen = false;
	private int lifeSetting = 0;
	private int timeLimit = 0;
	private Vibrator vibreur;
	
	//UI
	Typeface custom_font;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_startmenu);
		
		custom_font = Typeface.createFromAsset(getAssets(), "fonts/batmfa.ttf");
		
		//Get Main Interface
		background_top = (ImageView) findViewById(R.id.fondhaut);
		background_bottom = (ImageView) findViewById(R.id.fondbas);	
		pressStart = (ImageView) findViewById(R.id.press_start);
		title = (ImageView) findViewById(R.id.menu_title);
		playMode = (ImageView) findViewById(R.id.play_mode);
		freeMode = (ImageView) findViewById(R.id.free_mode);
		settings = (SlidingDrawer) findViewById(R.id.settings);
		
		//Get System Service
		vibreur = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		
		//Get WiFi Information Interface
		wifiLevel = (ImageView) findViewById(R.id.wifi_level);
		wifiName = (TextView) findViewById(R.id.wifi_name);
		wifiName.setTypeface(custom_font);
		wifiBackground = findViewById(R.id.wifi_background);
		
		//Get Settings Interface
		handle = (ImageView) findViewById(R.id.handle);
		//Display
		pseudoText = (TextView) findViewById(R.id.pseudo_value);
		pseudoText.setTypeface(custom_font);
		robotName = (TextView) findViewById(R.id.name_value);
		robotName.setTypeface(custom_font);
		//Change		
		changePseudo = (Button) findViewById(R.id.change_pseudo);
		changePseudo.setTypeface(custom_font);
		changeRobot = (Button) findViewById(R.id.change_myrobot);
		changeRobot.setTypeface(custom_font);
		alwaysCheck = (CheckBox) findViewById(R.id.always_check);
		changeName = (Button) findViewById(R.id.change_myname);
		changeName.setTypeface(custom_font);
		
		//Initialize WiFi Service
		networkManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		robotReceiver = new RobotReceiver();

		//Get settings file
		configuration = getPreferences(0);
		//Use Preferences to initialize settings
		getConfiguration();		

		//Initialize Intent Filters for BroadcastReceiver
		wifiReceiver = new WifiStateReceiver(this, wifiManager, configuration);
		actionFilter = new IntentFilter();
		actionFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		actionFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		actionFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		actionFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

		//Make Second Interface Invisible and keep First Interface Visible
		title.setVisibility(View.INVISIBLE);
		playMode.setVisibility(View.INVISIBLE);
		freeMode.setVisibility(View.INVISIBLE);
		settings.setVisibility(View.INVISIBLE);
		wifiBackground.setVisibility(View.INVISIBLE);

		//Set all Main Interface Listeners
		pressStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				
				Animation anim_top = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_top_up);
	            anim_top.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_top.setFillAfter(true);	            
	            Animation anim_bottom = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_bottom_down);
	            anim_bottom.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_bottom.setFillAfter(true);
	            Animation anim_start = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_disappear);
	            anim_start.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_start.setFillAfter(true);
	            
	            vibreur.vibrate(100);
	            pressStart.startAnimation(anim_start);
	            background_top.startAnimation(anim_top);
	            background_bottom.startAnimation(anim_bottom);
	            holoIsOpen = true;
	            new Thread(new Runnable() {					
					@Override
					public void run() {
						synchronized (this) {
							try {
								wait(1000);
								runOnUiThread(new Runnable() {									
									@Override
									public void run() {
										pressStart.setVisibility(View.INVISIBLE);
										pressStart.clearAnimation();
										wifiEnable();										
									}
								});								
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();				
			}
		});
		
		playMode.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				vibreur.vibrate(100);
				wifiReceiver.searchOtherPlayers();
			}
		});
		
		freeMode.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				vibreur.vibrate(100);
				Intent intent = new Intent(StartMenuActivity.this, GameActivity.class);
				intent.putExtra(GameActivity.GAME_MODE, GameActivity.FREE_MODE);
				startActivity(intent);
			}
		});

		settings.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				handle.setImageDrawable(getResources().getDrawable(R.drawable.settings_close_50));
			}
		});

		settings.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				handle.setImageDrawable(getResources().getDrawable(R.drawable.settings_open_50));
			}
		});
		
		//Set all Settings Interface Listeners
		changePseudo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setPseudo();
			}
		});

		changeRobot.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changeRobot();
			}
		});

		alwaysCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,	boolean isChecked) {
				SharedPreferences.Editor editor = configuration.edit();
				editor.putBoolean(ALWAYS, isChecked);
				if(isChecked) editor.putString(NAME, wifiManager.getConnectionInfo().getSSID());
				else editor.putString(NAME, "");
				editor.commit();
				getConfiguration();
			}
		});

		changeName.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changeName();
			}
		});
		
		//Set Invitation Receiver Listener
		robotReceiver.setOnCallReceiver(new OnCallReceiverListener() {
			@Override
			public void onCallReceiverListener(NewGameParameters newParams) {
				callBuilder = new AlertDialog.Builder(StartMenuActivity.this);
				callBuilder.setMessage(R.string.dia_mes_invitation);
				callBuilder.setNegativeButton(R.string.refuse, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				callBuilder.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(StartMenuActivity.this, GameActivity.class);
						intent.putExtra(GameActivity.GAME_MODE, GameActivity.VS_MODE);
						intent.putExtra(GameActivity.GAME_PARAM, newGameParam);
						startActivity(intent);
						dialog.dismiss();
					}
				});
				callAlert = callBuilder.create();
				if(!callAlert.isShowing()) callAlert.show();
			}
		});
	}
	
	/**
	 * Get SharedPreferences variables and change settings
	 * interface accordingly.
	 * Preferences are put in static variables.
	 */
	private void getConfiguration() {
		pseudo = configuration.getString(PSEUDO, "");
		always = configuration.getBoolean(ALWAYS, false);
		myName = configuration.getString(NAME, "");
		if (pseudo.isEmpty()) 
			setPseudo();
		else 
			pseudoText.setText(" " + pseudo);

		if (always) {
			if (myName.equals(wifiManager.getConnectionInfo().getSSID()))
				alwaysCheck.setChecked(true);
			else
				alwaysCheck.setChecked(false);
		} 
		else 
			alwaysCheck.setChecked(false);
	}

	/**
	 * Check if WiFi is enabled, if not, an AlertDialog asking
	 * the users if he wants to turn it on appear. WiFi connection
	 * is required to continue.
	 */
	private void wifiEnable() {
		if (!wifiManager.isWifiEnabled()) {
			alertBuilder = new AlertDialog.Builder(StartMenuActivity.this);
			alertBuilder.setMessage(R.string.dia_mes_wifienable);
			alertBuilder.setIcon(R.drawable.wifi_level_4_50);
			alertBuilder.setNegativeButton(R.string.cancel,	new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							enableWifi.dismiss();
						}
					});
			alertBuilder.setPositiveButton(R.string.ok,	new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							wifiManager.setWifiEnabled(true);
							enableWifi.dismiss();
							wifiManager.disconnect();
							wifiReceiver.connectRobot();
						}
					});
			enableWifi = alertBuilder.create();
			enableWifi.show();
		} else {
			NetworkInfo netInfo = networkManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);			
			if (netInfo.isConnected()){
				WifiInfo info = wifiManager.getConnectionInfo();
				String robot = info.getSSID().split("-")[0];
				if(robot.equals("Robot") || robot.equals("\"Robot")) {
					pressStart.setVisibility(View.INVISIBLE);
					title.setVisibility(View.VISIBLE);
					playMode.setVisibility(View.VISIBLE);
					freeMode.setVisibility(View.VISIBLE);
					settings.setVisibility(View.VISIBLE);
					wifiBackground.setVisibility(View.VISIBLE);
					onWifiStateChange(WifiStateReceiver.WIFI_CONNECTED, info.getSSID());
					onWifiPowerChange(info.getRssi());
				}
				else {
					wifiManager.disconnect();
					wifiReceiver.connectRobot();
				}
			}
			else {			
				wifiManager.disconnect();
				wifiReceiver.connectRobot();
			}
		}
	}

	/**
	 * Show a dialog asking the user for his new pseudo.
	 * Pseudo cannot be empty and and must be 10 characters maximum.
	 */
	private void setPseudo() {
		pseudoBuilder = new AlertDialog.Builder(this);
		pseudoBuilder.setTitle(R.string.dia_title_pseudo);
		pseudoLayout = getLayoutInflater().inflate(R.layout.pseudo_layout, null);
		pseudoValue = (EditText) pseudoLayout.findViewById(R.id.pseudo_val);
		pseudoBuilder.setView(pseudoLayout);
		pseudoBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				});
		pseudoAlert = pseudoBuilder.create();
		pseudoAlert.show();
		pseudoAlert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						String newPseudo = pseudoValue.getText().toString();
						if (newPseudo.isEmpty()) {
							Toast.makeText(StartMenuActivity.this, R.string.toast_emptypseudo, Toast.LENGTH_SHORT).show();
						} else if (newPseudo.length() > 10) {
							Toast.makeText(StartMenuActivity.this, R.string.toast_longpseudo, Toast.LENGTH_SHORT).show();
						} else {
							SharedPreferences.Editor editor = configuration.edit();
							editor.putString(PSEUDO, pseudoValue.getText().toString());
							editor.commit();
							getConfiguration();							
							pseudoAlert.dismiss();
						}
					}
				});
	}

	/**
	 * Show a dialog asking the user to confirm his choice
	 * to change the robot he is connected to.
	 */
	private void changeRobot() {
		robotBuilder = new AlertDialog.Builder(this);
		robotBuilder.setMessage(R.string.dia_mes_askconfirm);
		robotBuilder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						wifiManager.disconnect();
						wifiReceiver.changeRobot();
					}
				});
		robotBuilder.setNegativeButton(R.string.no,	new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		robotAlert = robotBuilder.create();
		robotAlert.show();
	}

	/**
	 * Show a dialog asking the user to write a new name for the robot.
	 * The name is set to start with "Robot-".
	 * The end of the name must not be empty and is limited to 10 characters.
	 */
	private void changeName() {

		nameBuilder = new AlertDialog.Builder(this);
		nameLayout = getLayoutInflater().inflate(R.layout.name_layout, null);
		nameBuilder.setTitle("Change Robot's name");
		nameBuilder.setView(nameLayout);
		nameValue = (EditText) nameLayout.findViewById(R.id.dia_value_name);
		nameBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									Socket socket = new Socket(SERVERIP, SERVERPORT);
									OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
									out.write("Robot-" + nameValue.getText());
									out.flush();
								} catch (UnknownHostException ex) {
									Log.e("NetError", ex.getMessage());
								} catch (IOException ex) {
									Log.e("NetError", ex.getMessage());
								}
							}
						}).start();
						
						timeBuilder = new AlertDialog.Builder(StartMenuActivity.this);
						timeBuilder.setMessage(R.string.dia_mes_timewarn);
						timeBuilder.setPositiveButton(R.string.ok,	new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,	int id) {
										settings.close();
										dialog.dismiss();
									}
								});
						timeAlert = timeBuilder.create();
						dialog.dismiss();
						timeAlert.show();
					}
				});
		nameBuilder.setNegativeButton(R.string.cancel,	new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
		});
		nameAlert = nameBuilder.create();
		nameAlert.show();
	}

	@Override
	public void onResume() {
		super.onResume();
		registerReceiver(wifiReceiver, actionFilter);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		unregisterReceiver(wifiReceiver);
	}

	/**
	 * WiFi State change listener.
	 * Change screen display based on the WiFi connection state.
	 */
	@Override
	public void onWifiStateChange(int state, String name) {
		if (state == WifiStateReceiver.WIFI_CONNECTED) {
			//Make Second Interface Visible and make First Interface Invisible
			if(holoIsOpen && !DIALOG_IS_SHOWING) {
				pressStart.setVisibility(View.INVISIBLE);
				title.setVisibility(View.VISIBLE);
				playMode.setVisibility(View.VISIBLE);
				freeMode.setVisibility(View.VISIBLE);
				settings.setVisibility(View.VISIBLE);
				wifiBackground.setVisibility(View.VISIBLE);
				wifiName.setText("" + name);
				robotName.setText(" " + name);
				if (myName.equals(name))
					alwaysCheck.setChecked(true);
				else
					alwaysCheck.setChecked(false);
			}			
		} else if (state == WifiStateReceiver.WIFI_DISCONNECTED) {
			//Make Second Interface Invisible and make First Interface Visible			
			if(holoIsOpen && !DIALOG_IS_SHOWING) {
				pressStart.setVisibility(View.VISIBLE);
				title.setVisibility(View.INVISIBLE);
				playMode.setVisibility(View.INVISIBLE);
				freeMode.setVisibility(View.INVISIBLE);
				settings.setVisibility(View.INVISIBLE);
				wifiBackground.setVisibility(View.INVISIBLE);
				Animation anim_top = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_top_down);
	            anim_top.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_top.setFillAfter(true);	            
	            Animation anim_bottom = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_bottom_up);
	            anim_bottom.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_bottom.setFillAfter(true);	
	            Animation anim_start = AnimationUtils.loadAnimation(StartMenuActivity.this, R.anim.animation_start_appear);
	            anim_start.setInterpolator((new AccelerateDecelerateInterpolator()));
	            anim_start.setFillAfter(true);
	            
	            pressStart.setAnimation(anim_start);
	            background_top.startAnimation(anim_top);
	            background_bottom.startAnimation(anim_bottom);
	            holoIsOpen = false;
	            
	            new Thread(new Runnable() {					
					@Override
					public void run() {
						synchronized (this) {
							try {
								wait(1000);
								runOnUiThread(new Runnable() {									
									@Override
									public void run() {
										pressStart.setVisibility(View.VISIBLE);										
									}
								});								
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();	
			}
			wifiName.setText("");
			robotName.setText("");			
		}
	}

	/**
	 * WiFi Power change listener.
	 * Change image based on the power of the WiFi signal
	 */
	@Override
	public void onWifiPowerChange(int power) {
		if (power >= WifiStateReceiver.RSSI_MAX) {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_4_50));
		} else if (power < WifiStateReceiver.RSSI_MAX
				&& power >= (WifiStateReceiver.RSSI_MAX - WifiStateReceiver.RSSI_STEP_4)) {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_3_50));
		} else if (power < (WifiStateReceiver.RSSI_MAX - WifiStateReceiver.RSSI_STEP_4)
				&& power >= (WifiStateReceiver.RSSI_MAX - 2 * WifiStateReceiver.RSSI_STEP_4)) {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_2_50));
		} else if (power < (WifiStateReceiver.RSSI_MAX - WifiStateReceiver.RSSI_STEP_4)
				&& power >= WifiStateReceiver.RSSI_MIN) {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_1_50));
		} else if (power < WifiStateReceiver.RSSI_MIN) {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_0_50));
		} else {
			wifiLevel.setImageDrawable(getResources().getDrawable(R.drawable.wifi_level_0_50));
		}
	}

	/**
	 * Game created listener.
	 * Start a vs game with the parameters set by this user.
	 */
	@Override
	public void onGameCreated(NewGameParameters newGame) {
		newGameParam = newGame;
		
		configBuilder = new AlertDialog.Builder(this);			
		configBuilder.setTitle(R.string.dia_title_gameparam);
		paramLayout = getLayoutInflater().inflate(R.layout.newgame_layout,null);
		configBuilder.setView(paramLayout);		
		lifeLevel = (ProgressBar) paramLayout.findViewById(R.id.dia_life_level);
		lifeLess = (ImageView) paramLayout.findViewById(R.id.dia_lifeless_but);
		lifeMore = (ImageView) paramLayout.findViewById(R.id.dia_lifemore_but);
		lifeValue = (TextView) paramLayout.findViewById(R.id.dia_life_value);
		
		checkTimeLimited = (CheckBox) paramLayout.findViewById(R.id.dia_timelim_check);
		timeLevel = (ProgressBar) paramLayout.findViewById(R.id.dia_time_level);
		timeLess = (ImageView) paramLayout.findViewById(R.id.dia_timeless_but);
		timeMore = (ImageView) paramLayout.findViewById(R.id.dia_timemore_but);
		timeValue = (TextView) paramLayout.findViewById(R.id.dia_time_value);
		
		lifeSetting = 100;
		lifeValue.setText("" + lifeSetting);
		
		timeMore.setEnabled(false);
		timeLess.setEnabled(false);
		timeLevel.setEnabled(false);
		timeLimit = 0;
		timeValue.setText("");
		timeLevel.setProgress(timeLimit);
		
		lifeLess.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(lifeSetting > HEALTH_MIN) {
						lifeSetting -=10;
						lifeLevel.setProgress(lifeSetting);
						lifeValue.setText("" + lifeSetting);
					}
				}
		});
		lifeMore.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(lifeSetting < HEALTH_MAX) {
						lifeSetting +=10;
						lifeLevel.setProgress(lifeSetting);
						lifeValue.setText("" + lifeSetting);
					}
				}
		});
		checkTimeLimited.setOnCheckedChangeListener(new OnCheckedChangeListener() {			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) {
					timeMore.setEnabled(true);
					timeLess.setEnabled(true);
					timeLimit = 15;
					timeLevel.setProgress(timeLimit);
					timeValue.setText("" + timeLimit);
				}
				else {
					timeMore.setEnabled(false);
					timeLess.setEnabled(false);
					timeLimit = 0;
					timeLevel.setProgress(timeLimit);
					timeValue.setText("");
				}
			}
		});
		timeLess.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(timeLimit > TIME_MIN) {
					timeLimit -= 5;
					timeLevel.setProgress(timeLimit);
					timeValue.setText("" + timeLimit);
				}
			}
		});
		timeMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(timeLimit < TIME_MAX) {
					timeLimit += 5;
					timeLevel.setProgress(timeLimit);
					timeValue.setText("" + timeLimit);
				}
			}
		});
		configBuilder.setPositiveButton(R.string.create,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						newGameParam.setLifeMax(lifeSetting);
						newGameParam.setTimeLimit(timeLimit);
						waitBuilder = new AlertDialog.Builder(StartMenuActivity.this);						
						waitLayout = getLayoutInflater().inflate(R.layout.waiting_layout,null);
						waitBuilder.setView(waitLayout);
						waitBuilder.setNeutralButton(R.string.skip, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {								
								Intent intent = new Intent(StartMenuActivity.this, GameActivity.class);
								intent.putExtra(GameActivity.GAME_MODE, GameActivity.VS_MODE);
								intent.putExtra(GameActivity.GAME_PARAM, newGameParam);
								startActivity(intent);
								dialog.dismiss();
							}
						});
						waitAlert = waitBuilder.create();
						dialog.dismiss();
						waitAlert.show();
				}
		});		
		configAlert = configBuilder.create();
		configAlert.show();
	}
}
